<template>
  <div class="tasks-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><DocumentChecked /></el-icon>
          <div class="header-text">
            <h2>任务管理</h2>
            <p>个人和团队任务跟踪</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showDialog = true">
            <el-icon><Plus /></el-icon>
            新建任务
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 任务统计卡片 -->
    <div class="stats-row">
      <el-card shadow="hover" class="stat-card" @click="filterStatus = ''">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#409EFF"><List /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">全部任务</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card" @click="filterStatus = 'pending'">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#E6A23C"><Clock /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.pending }}</div>
            <div class="stat-label">待处理</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card" @click="filterStatus = 'processing'">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#409EFF"><Loading /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.processing }}</div>
            <div class="stat-label">进行中</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card" @click="filterStatus = 'completed'">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#67C23A"><CircleCheck /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card" @click="filterStatus = 'overdue'">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#F56C6C"><WarningFilled /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.overdue }}</div>
            <div class="stat-label">已逾期</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 任务列表 -->
    <el-card shadow="never">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="我的任务" name="my" />
        <el-tab-pane label="我创建的" name="created" />
        <el-tab-pane label="我参与的" name="joined" />
        <el-tab-pane label="全部任务" name="all" />
      </el-tabs>

      <el-table :data="filteredTasks" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="任务标题" min-width="200">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; gap: 8px;">
              <el-icon v-if="row.priority === 'high'" color="#F56C6C"><WarningFilled /></el-icon>
              <el-text class="task-title" @click="handleView(row)" style="cursor: pointer; color: #409EFF;">
                {{ row.title }}
              </el-text>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">
              {{ getPriorityName(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignee" label="负责人" width="100" />
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="deadline" label="截止日期" width="160">
          <template #default="{ row }">
            <span :style="{ color: isOverdue(row.deadline) ? '#F56C6C' : '' }">
              {{ row.deadline }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :status="getProgressStatus(row.progress)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button link type="success" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="warning" @click="handleComplete(row)" v-if="row.status !== 'completed'">
              <el-icon><CircleCheck /></el-icon>
              完成
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- 新建/编辑任务对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="dialogTitle"
      width="700px"
      destroy-on-close
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入任务标题" />
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入任务描述" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
                <el-option label="紧急" value="urgent" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="assignee">
              <el-select v-model="form.assignee" placeholder="请选择负责人" style="width: 100%">
                <el-option label="张三" value="1" />
                <el-option label="李四" value="2" />
                <el-option label="王五" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="deadline">
              <el-date-picker
                v-model="form.deadline"
                type="date"
                placeholder="选择截止时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="参与人员" prop="participants">
          <el-select v-model="form.participants" multiple placeholder="请选择参与人员" style="width: 100%">
            <el-option label="张三" value="1" />
            <el-option label="李四" value="2" />
            <el-option label="王五" value="3" />
            <el-option label="赵六" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务标签" prop="tags">
          <el-select v-model="form.tags" multiple allow-create filterable placeholder="请选择或输入标签" style="width: 100%">
            <el-option label="重要" value="important" />
            <el-option label="紧急" value="urgent" />
            <el-option label="开发" value="dev" />
            <el-option label="测试" value="test" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  DocumentChecked, Plus, List, Clock, Loading, CircleCheck, WarningFilled,
  View, Edit, Delete
} from '@element-plus/icons-vue'

// 状态
const activeTab = ref('my')
const filterStatus = ref('')

// 统计数据
const stats = reactive({
  total: 45,
  pending: 12,
  processing: 18,
  completed: 10,
  overdue: 5
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 45
})

// 任务数据
const tasks = ref([
  {
    id: 1,
    title: '完成项目需求文档',
    priority: 'high',
    status: 'processing',
    assignee: '张三',
    creator: '李四',
    deadline: '2024-01-20',
    progress: 60
  },
  {
    id: 2,
    title: '系统功能测试',
    priority: 'medium',
    status: 'pending',
    assignee: '李四',
    creator: '张三',
    deadline: '2024-01-22',
    progress: 0
  },
  {
    id: 3,
    title: '数据库优化',
    priority: 'urgent',
    status: 'processing',
    assignee: '王五',
    creator: '赵六',
    deadline: '2024-01-15',
    progress: 80
  },
  {
    id: 4,
    title: '用户界面设计',
    priority: 'low',
    status: 'completed',
    assignee: '赵六',
    creator: '张三',
    deadline: '2024-01-10',
    progress: 100
  },
  {
    id: 5,
    title: '代码审查',
    priority: 'high',
    status: 'overdue',
    assignee: '张三',
    creator: '李四',
    deadline: '2024-01-12',
    progress: 30
  }
])

// 对话框
const showDialog = ref(false)
const formRef = ref(null)
const currentTask = ref(null)
const dialogTitle = computed(() => currentTask.value ? '编辑任务' : '新建任务')

// 表单
const form = reactive({
  title: '',
  description: '',
  priority: 'medium',
  assignee: '',
  startTime: null,
  deadline: null,
  participants: [],
  tags: []
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
  assignee: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  deadline: [{ required: true, message: '请选择截止时间', trigger: 'change' }]
}

// 计算属性
const filteredTasks = computed(() => {
  let result = tasks.value
  if (filterStatus.value) {
    result = result.filter(t => t.status === filterStatus.value)
  }
  return result
})

// 方法
const handleTabClick = () => {
  console.log('切换标签', activeTab.value)
}

const handleView = (row) => {
  ElMessageBox.alert(
    `任务描述：完成相关工作...\n负责人：${row.assignee}\n截止时间：${row.deadline}\n进度：${row.progress}%`,
    row.title,
    { confirmButtonText: '确定', type: 'info' }
  )
}

const handleEdit = (row) => {
  currentTask.value = row
  Object.assign(form, {
    title: row.title,
    description: '任务描述...',
    priority: row.priority,
    assignee: '1',
    startTime: null,
    deadline: row.deadline,
    participants: [],
    tags: []
  })
  showDialog.value = true
}

const handleComplete = (row) => {
  ElMessageBox.confirm('确定要标记该任务为已完成吗？', '提示', {
    type: 'success'
  }).then(() => {
    row.status = 'completed'
    row.progress = 100
    ElMessage.success('任务已完成')
  }).catch(() => {})
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = tasks.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tasks.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功')
      showDialog.value = false
    }
  })
}

const isOverdue = (deadline) => {
  return new Date(deadline) < new Date()
}

const getPriorityName = (priority) => {
  const map = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return map[priority] || priority
}

const getPriorityType = (priority) => {
  const map = {
    low: 'info',
    medium: '',
    high: 'warning',
    urgent: 'danger'
  }
  return map[priority] || ''
}

const getStatusName = (status) => {
  const map = {
    pending: '待处理',
    processing: '进行中',
    completed: '已完成',
    overdue: '已逾期'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    processing: '',
    completed: 'success',
    overdue: 'danger'
  }
  return map[status] || ''
}

const getProgressStatus = (progress) => {
  if (progress === 100) return 'success'
  if (progress >= 80) return ''
  if (progress >= 50) return 'warning'
  return 'exception'
}
</script>

<style scoped>
.tasks-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.task-title:hover {
  text-decoration: underline;
}
</style>

